package com.gk.chat.filter;

import com.gk.chat.common.TokenContext;
import com.gk.chat.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    //通过构造函数注入JwtUtil
    @Autowired
    public JwtAuthenticationFilter(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Autowired
    private TokenContext tokenContext;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token=request.getHeader("Authorization");
        if(token!=null&&token.startsWith("Bearer")){
            token=token.substring(7);
            try{
                Map<String,Object> claims= jwtUtil.parseToken(token);
                String username=(String)claims.get("mobile");
                //构建认证对象
                UsernamePasswordAuthenticationToken authentication=new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }catch (Exception e){
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"token无效");
            }
        }
        tokenContext.setToken(token);
        chain.doFilter(request,response);
    }
}
